package info.heidao.ww2.common.convert;

import cn.hutool.core.bean.BeanUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 属性拷贝
 * <p>
 * author zhengheng
 *
 * @since 2019-11-29
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PojoConverter {

    /**
     * 转换对象
     *
     * @param from    原始对象
     * @param toClass 新对象Class
     * @param <T>     对象类型
     * @return 新对象
     */
    public static <F, T> T convert(F from, Class<T> toClass, String... ignoreProperties) {
        return Optional.ofNullable(from)
                .map(f -> {
                    T t = BeanUtils.instantiateClass(toClass);
                    BeanUtil.copyProperties(f, t, ignoreProperties);
                    return t;
                })
                .orElse(null);
    }

    /**
     * 转换对象集合
     *
     * @param collect 原始对象集合
     * @param toClass 新对象Class
     * @param <T>     对象类型
     * @return 新对象集合
     */
    public static <F, T> List<T> conventList(Collection<F> collect, Class<T> toClass, String... ignoreProperties) {
        return Optional.ofNullable(collect)
                .orElseGet(Collections::emptyList)
                .stream()
                .map(from -> convert(from, toClass, ignoreProperties))
                .collect(Collectors.toList());
    }

}
